package com.baizhi.controller;

import com.baizhi.entity.Product;
import com.baizhi.service.impl.ProductServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProductController {
    @Value("${imgPath}")
    private String path;
    @Autowired
    private ProductServiceImpl pd;
    @GetMapping("products")
    public Map<String,Object> selectAll(int page, int limit){
        PageInfo<Product> pageInfo = pd.selectByPage(page, limit);
        return new HashMap(){{
           put("msg","");
           put("code",0);
           put("data",pageInfo.getList());
           put("count",pageInfo.getTotal());
        }};
    }
    @DeleteMapping("products")
    public void deleteMany(@RequestBody List<Integer> ids){
        for (Integer id : ids) {
            pd.delete(id);
        }
    }
    @PostMapping("uploads")
    public Map<String,Object> upload(MultipartFile file){
        try {
            file.transferTo(new File(path,file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap(){{
            put("msg",file.getOriginalFilename());
            put("code",0);
        }};
    }
    @PostMapping("products")
    public void insert(@RequestBody Product p){
        pd.addImg(p);
    }
}
